package com.ysd.lis.service.bac.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.util.ToolsUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BacBreakPointCalcServiceImpl extends ServiceImpl<BacBreakPointMapper, BacBreakPoint> {
    private static final Logger logger = LoggerFactory.getLogger(BacBreakPointCalcServiceImpl.class);
    @Autowired
    BacGermDictMapper bacGermDictMapper;
    @Autowired
    BacAntibioticsDictMapper bacAntibioticsDictMapper;
    @Autowired
    BacBreakPointMapper bacBreakPointMapper;
    @Autowired
    BacSiteOfInfectionDictMapper bacSiteOfInfectionDictMapper;
    @Autowired
    BacAstTestMthDictMapper bacAstTestMthDictMapper;
    @Autowired
    BacInterpretationCodeDictMapper bacInterpretationCodeDictMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    private List<BacBreakPoint> breakpoints;
    private List<BacAntibioticsDict> ants;
    private List<BacSiteOfInfectionDict> SiteOfInfections = new ArrayList<>();
    private List<BacAstTestMthDict> ASTTestMethods = new ArrayList<>();
    private List<BacInterpretationCodeDict> InterpretationCodes = new ArrayList<>();

    public void setApplicableBreakpoint(BacTestResult identificationResult, List<BacDrugTestResult> astResults, boolean setBreakpoint, boolean setInterpretationCode) {
        if (false) {
            return;/*关闭折点结算*/
        }
        if (astResults == null || astResults.isEmpty()) {
            return;
        }

        if (identificationResult == null) {
            return;
        }

        // 查找细菌
        if (identificationResult.getId() == null || ToolsUtils.isEmpty(identificationResult.getId())) {
            return;
        }

        LambdaQueryWrapper<BacGermDict> germQueryWrapper = new LambdaQueryWrapper<>();
        germQueryWrapper.eq(BacGermDict::getDelFlag, 0);
        germQueryWrapper.eq(BacGermDict::getGermNo, identificationResult.getGermNo());

        BacGermDict bacGermDict = bacGermDictMapper.selectOne(germQueryWrapper);//getWithDetails().stream().filter(p -> p.getId().equals(identificationResult.getOrgId())).findFirst().orElse(null);

        // 细菌不存在
        if (bacGermDict == null) {
            return;
        }

        loadDictsAsync();


        // 指南
        List<String> prioritizedGuidelines = Arrays.asList("CLSI", "EUCAST");

        // 用户自定义折点
        String userDefinedGuideline = "AUser-defined";

        // 年份
        List<String> prioritizedGuidelineYears = getPastTenYears(); //Arrays.asList("2023", "2022", "2021", "2020", "2019");

        // 折点类型
        List<String> prioritizedBreakpointTypes = Arrays.asList("Human", "ECOFF");

        // 感染部位
        String siteOfInfectionId = Optional.ofNullable(identificationResult.getInfeSiteNo()).orElse("");

        BacSiteOfInfectionDict siteOfInfection = SiteOfInfections.stream().filter(p -> p.getCode().equals(siteOfInfectionId)).findFirst().orElse(null);

        String prioritizedSitesOfInfection = (siteOfInfection != null) ? siteOfInfection.getStandardName() : null;

        // 抗生素
        List<String> antIds = astResults.stream().map(BacDrugTestResult::getAntNo).distinct().collect(Collectors.toList());

        LambdaQueryWrapper<BacAntibioticsDict> antQueryWrapper = new LambdaQueryWrapper<>();
        antQueryWrapper.eq(BacAntibioticsDict::getDelFlag, 0);
        antQueryWrapper.in(BacAntibioticsDict::getAntCode, antIds);

        List<BacAntibioticsDict> ants = bacAntibioticsDictMapper.selectList(antQueryWrapper);//antRepository.getWithDetails().stream().filter(p -> antIds.contains(p.getId())).collect(Collectors.toList());

        //查询折点数据
        LambdaQueryWrapper<BacBreakPoint> breakpointQueryWrapper = new LambdaQueryWrapper<>();
        breakpointQueryWrapper.eq(BacBreakPoint::getDelFlag, 0);
        breakpointQueryWrapper.ge(BacBreakPoint::getYear, Integer.parseInt(prioritizedGuidelineYears.get(prioritizedGuidelineYears.size() - 1)));
        breakpointQueryWrapper.isNotNull(BacBreakPoint::getWhonetTest);
        breakpointQueryWrapper.in(BacBreakPoint::getWhonetAbxCode, antIds);
        List<BacBreakPoint> breakpoints = bacBreakPointMapper.selectList(breakpointQueryWrapper);

        // 必要条件过滤
        breakpoints = breakpoints.stream().filter(bp -> {
            return prioritizedGuidelineYears.contains(bp.getYear().toString());
        }).filter(bp -> {
            boolean r = prioritizedGuidelines.contains(bp.getGuidelines());
            boolean r2 = userDefinedGuideline.equals(bp.getGuidelines());
            return r || r2;
        }).filter(bp -> {
            return prioritizedBreakpointTypes.contains(bp.getBreakpointType());
        }).collect(Collectors.toList());

        breakpoints = breakpoints.stream()
                .filter(bp ->
                        // 条件 1: 血清组
                        (ToolsUtils.isNotEmpty(bacGermDict.getSerumGroup())
                                && bacGermDict.getSerumGroup().equals(bp.getSerovarGroup()))
                                // 条件 2: 微生物
                                || (ToolsUtils.isNotEmpty(bacGermDict.getGermNo())
                                && (bacGermDict.getGermNo().equals(bp.getWhonetOrgCode())) && "AUser-defined".equals(bp.getGuidelines()))
                                || (ToolsUtils.isNotEmpty(bacGermDict.getWhoCode())
                                && (bacGermDict.getWhoCode().equals(bp.getWhonetOrgCode())) && !"AUser-defined".equals(bp.getGuidelines()))
                                // 条件 3: 种
                                || (ToolsUtils.isNotEmpty(bacGermDict.getSpeciesGroup())
                                && bacGermDict.getSpeciesGroup().equals(bp.getSpeciesGroup()))
                                // 条件 4: 属编号
                                || (ToolsUtils.isNotEmpty(bacGermDict.getGenusCode())
                                && bacGermDict.getGenusCode().equals(bp.getGenusCode()))
                                // 条件 5: 属
                                || (ToolsUtils.isNotEmpty(bacGermDict.getGenusGroup())
                                && bacGermDict.getGenusGroup().equals(bp.getGenusGroup()))
                                // 条件 6: 科
                                || (ToolsUtils.isNotEmpty(bacGermDict.getFamilyCode())
                                && bacGermDict.getFamilyCode().equals(bp.getFamilyCode()))
                                // 条件 7: 厌氧 & 门
                                || (ToolsUtils.isNotEmpty(bacGermDict.getIsAnaerobe())
                                && ToolsUtils.isNotEmpty(bacGermDict.getSubKingdomCode())
                                && bacGermDict.getSubKingdomCode().equals(bp.getSubkingdomCode())
                                && ToolsUtils.isNotEmpty(bp.getAnaerobe())
                                && "ANA".equals(bp.getAnaerobe().toUpperCase())
                                && bp.getAnaerobe().equals(1))
                                // 条件 8: 厌氧
                                || (ToolsUtils.isNotEmpty(bacGermDict.getIsAnaerobe())
                                && ToolsUtils.isNotEmpty(bp.getAnaerobe())
                                && "ANA".equals(bp.getAnaerobe().toUpperCase())
                                && bacGermDict.getIsAnaerobe().equals(1))
                )
                .collect(Collectors.toList());

        for (BacDrugTestResult astResult : astResults) {
            String antId = astResult.getAntNo();

            BacAntibioticsDict ant = ants.stream().filter(p -> p.getAntCode().equals(antId)).findFirst().orElse(null);

            if (ant == null) {
                continue;
            }

            String aSTTestMethodId = astResult.getDrugMthNo();

            BacAstTestMthDict aSTTestMethod = ASTTestMethods.stream().filter(p -> p.getCode().equals(aSTTestMethodId)).findFirst().orElse(null);

            if (aSTTestMethod == null) {
                continue;
            }

            String whoNetAbxCode = ant.getWhonetAbxCode();

            List<BacBreakPoint> lstFilter = breakpoints.stream().filter(p ->/*抗生素*/p.getWhonetAbxCode().equals(antId) && p.getTestMethod().equals(aSTTestMethodId)).collect(Collectors.toList());

            if (ToolsUtils.isEmpty(lstFilter)) {
                //setEmptyBreakpointInfoTwo(astResult);
                continue;
            }
            List<Map<String, Object>> siteOfList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("siteOfInfectionList").getData();
            List<String> stringList = (List<String>) siteOfList.stream()
                    .sorted(Comparator.comparing(map -> (Comparable) map.get("sx")))
                    .map(map -> (String) ((Map<?, ?>) map).get("code"))
                    .collect(Collectors.toList());
            lstFilter = lstFilter.stream()
                    .sorted(Comparator.comparing(BacBreakPoint::getGuidelines)
                            // Year
                            .thenComparing(bp -> ToolsUtils.isEmpty(bp.getYear()) ? 9999999 : Integer.parseInt(bp.getYear().toString()), Comparator.reverseOrder())
                            // ASTTestMethod
                            .thenComparing(BacBreakPoint::getTestMethod, Comparator.nullsLast(String::compareTo))
                            // BreakpointType
                            .thenComparing(bp -> {
                                if (ToolsUtils.isEmpty(bp.getBreakpointType())) return 9;
                                if ("Human".equals(bp.getBreakpointType())) return 1;
                                if ("ECOFF".equals(bp.getBreakpointType())) return 2;
                                return 9;
                            })
                            // Host
                            .thenComparing(BacBreakPoint::getHost, Comparator.nullsLast(String::compareTo))

                    )
                    .collect(Collectors.toList());


            // SiteOfInfections
            if(ToolsUtils.isNotEmpty(prioritizedSitesOfInfection)){
                //将lstFilter中SiteOfInfection与prioritizedSitesOfInfection相同得排序在前边
                lstFilter.sort((bp1, bp2) -> {
                    boolean match1 = bp1.getSiteOfInfection() != null && prioritizedSitesOfInfection.contains(bp1.getSiteOfInfection());
                    boolean match2 = bp2.getSiteOfInfection() != null && prioritizedSitesOfInfection.contains(bp2.getSiteOfInfection());

                    if (match1 && !match2) return -1;
                    if (!match1 && match2) return 1;
                    return 0;
                });
//                lstFilter = lstFilter.stream()
//                        .sorted(Comparator.comparing(bp -> {
//                                    if (ToolsUtils.isEmpty(bp.getSiteOfInfection())) {
//                                        return 0;
//                                    }
//                           /*     List<String> categories = Arrays.asList(
//                                        "NonMeningitis", "Parenteral", "None", "UTI", "Meningitis", "Intravenous", "Oral",
//                                        "Inhaled", "InvestigationalAgent", "Extraintestinal", "Abscesses", "Genital",
//                                        "Intestinal", "Liposomal", "MammaryGland", "Metritis", "NonPneumonia", "OtherInfections",
//                                        "Pneumonia", "Prophylaxis", "Respiratory", "Screen", "Skin", "SoftTissue", "Wounds"
//                                );*/
//                                    if (stringList.contains(bp.getSiteOfInfection())) {
//                                        int i = stringList.indexOf(bp.getSiteOfInfection());
//                                        return stringList.indexOf(bp.getSiteOfInfection());
//                                    }
//                                    if (ToolsUtils.isNotEmpty(prioritizedSitesOfInfection)) {
//                                        int i = prioritizedSitesOfInfection.indexOf(bp.getSiteOfInfection().toLowerCase());
//                                        return prioritizedSitesOfInfection.indexOf(bp.getSiteOfInfection().toLowerCase());
//                                    }
//                                    return 999;
//
//                                })
//                        )
//                        .collect(Collectors.toList());

            }
            if (ToolsUtils.isNotEmpty(antIds) && antIds.get(0).equals("CXM")) {
                String aa = "";
            }

            BacBreakPoint applicableBreakpoint = lstFilter.stream().findFirst().orElse(null);//stream().filter(p -> /*抗生素*/p.getWhonetAbxCode().equals(antId) && p.getTestMethod().equals(aSTTestMethodId)).findFirst().orElse(null);

            //List<BacDrugTestResult> emptyList = new ArrayList<>();
            //emptyList.add(astResult);

            if (applicableBreakpoint == null) {
                //setEmptyBreakpointInfo(emptyList, false, false);
                setEmptyBreakpointInfoOne(astResult, false, false);
                continue;
            }
            //setEmptyBreakpointInfo(emptyList, setBreakpoint, setInterpretationCode);
            setEmptyBreakpointInfoOne(astResult, setBreakpoint, setInterpretationCode);


            if (setBreakpoint) {
                astResult.setBreakPoint(applicableBreakpoint.getRef());
            }

            // 设置 Breakpoint 冗余数据
            astResult.setBreakPointId(applicableBreakpoint.getId());
            astResult.setGuideline(applicableBreakpoint.getGuidelines());
            astResult.setYear(applicableBreakpoint.getYear().toString());
            astResult.setWhonetTest(applicableBreakpoint.getWhonetTest());
            astResult.setBreakPointType(applicableBreakpoint.getBreakpointType());
            astResult.setHost(applicableBreakpoint.getHost());
            astResult.setWhonetTest(applicableBreakpoint.getWhonetTest());
            if(ToolsUtils.isNotEmpty(applicableBreakpoint.getPotency())){
                astResult.setPotency(applicableBreakpoint.getPotency());
            }
            astResult.setInfeSite(applicableBreakpoint.getSiteOfInfection());
            try {
                String r = applicableBreakpoint.getR();
                if(ToolsUtils.isNotEmpty(r)){
                    if(r.contains("/")){
                        astResult.setR(new BigDecimal(r.split("/")[0]));
                    }else {
                        astResult.setR(new BigDecimal(r));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            astResult.setI(applicableBreakpoint.getI());
            astResult.setSdd(applicableBreakpoint.getSdd());
            try {
                String s = applicableBreakpoint.getS();
                if(ToolsUtils.isNotEmpty(s)){
                    if(s.contains("/")){
                        astResult.setS(new BigDecimal(s.split("/")[0]));
                    }else {
                        astResult.setS(new BigDecimal(applicableBreakpoint.getS()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(ToolsUtils.isNotEmpty(applicableBreakpoint.getEcvEcoff())){
                    astResult.setEcoff(new BigDecimal(applicableBreakpoint.getEcvEcoff()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            astResult.setRefTable(applicableBreakpoint.getReferenceTable());
            astResult.setBreakPointRef(applicableBreakpoint.getRef());
            astResult.setSerovarGroup(applicableBreakpoint.getSerovarGroup());
            astResult.setWhonetOrgCode(applicableBreakpoint.getWhonetOrgCode());
            astResult.setSpeciesGroup(applicableBreakpoint.getSpeciesGroup());
            astResult.setGenusCode(applicableBreakpoint.getGenusCode());
            astResult.setGenusGroup(applicableBreakpoint.getGenusGroup());
            astResult.setFamilyCode(applicableBreakpoint.getFamilyCode());
            astResult.setAnaerobe(applicableBreakpoint.getAnaerobe());
            astResult.setSubkingdomCode(applicableBreakpoint.getSubkingdomCode());
            // 转换结果
            BigDecimal[] result = new BigDecimal[1];
            StringBuilder formattedASTResult = new StringBuilder();
            boolean formattedASTResultRes = transResult(astResult.getTestResult(), formattedASTResult, result);
            if (!formattedASTResultRes) {
                continue;
            }

            astResult.setTestResult(formattedASTResult.toString());

            if (setInterpretationCode) {
                BacInterpretationCodeDict interpretationCode = getInterpretationCode(aSTTestMethod, result[0], applicableBreakpoint);
                if (interpretationCode == null) {
                    continue;
                }
                astResult.setSensitiveNo(interpretationCode.getCode());
                astResult.setInterpNa(interpretationCode.getName());
                astResult.setInterpDisplayColor(interpretationCode.getDisplayColor());
                astResult.setSensitiveFrom("折点");

            }
        }
    }

    /*处理、转换结果*/
    public boolean transResult(String astResult, StringBuilder formattedASTResult, BigDecimal[] result) {
        if (false) {
            return false;/*关闭折点结算*/
        }
        formattedASTResult.setLength(0);  // Clear the previous content
        formattedASTResult.append(astResult);

        result[0] = BigDecimal.ZERO;

        if (ToolsUtils.isEmpty(astResult)) {
            formattedASTResult.setLength(0);  // Clear the formatted result if input is empty or null
            return false;
        }

        // Replace measurement symbols with constants
        formattedASTResult.replace(0, formattedASTResult.length(), formattedASTResult.toString().replace("＝", "=").replace("＞", ">").replace("＜", "＜").replace("≤", "≤").replace("≥", "≥"));

        // Try parsing the result with different modifiers
        if (tryParseResult(formattedASTResult.toString(), "", result)) {
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), ">=", result)) {
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), "≥", result)) {
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), "<=", result)) {
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), "≤", result)) {
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), "<", result)) {
            result[0] = result[0].subtract(new BigDecimal("0.000001"));
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), ">", result)) {
            result[0] = result[0].add(new BigDecimal("0.000001"));
            return true;
        }

        if (tryParseResult(formattedASTResult.toString(), "=", result)) {
            return true;
        }

        if (tryParseResultWithFXG(formattedASTResult.toString(), "/", result)) {
            return true;
        }

        return false;
    }

    /*去调结果中的符号*/
    private boolean tryParseResult(String astResult, String modifier, BigDecimal[] result) {

        if (modifier != null && !modifier.trim().isEmpty()) {
            int modifierIndex = astResult.indexOf(modifier);

            if (modifierIndex >= 0) {
                astResult = astResult.substring(modifierIndex + modifier.length());
            }
        }

        try {
            //如果存在/则需要去掉/后边的数据
            if (astResult.contains("/")) {
                String[] parts = astResult.split("/");
                astResult = parts[0];
            }
            //如果存在~ 则取~后边的数据
            if (astResult.contains("~")) {
                String[] parts = astResult.split("~");
                astResult = parts[1];
            }
            result[0] = new BigDecimal(astResult);  // Parse the result as BigDecimal
            return true;
        } catch (NumberFormatException e) {
            return false;  // Return false if parsing fails
        }
    }

    /*去调结果中的符号带反斜杠*/
    private boolean tryParseResultWithFXG(String astResult, String modifier, BigDecimal[] result) {

        if (modifier != null && !modifier.trim().isEmpty()) {
            int modifierIndex = astResult.indexOf(modifier);

            if (modifierIndex >= 0) {
                astResult = astResult.substring(0, modifierIndex);
            }
        }

        try {
            result[0] = new BigDecimal(astResult);  // Parse the result as BigDecimal
            return true;
        } catch (NumberFormatException e) {
            return false;  // Return false if parsing fails
        }
    }

    /*清空折点信息*/
    private void setEmptyBreakpointInfo(List<BacDrugTestResult> astResults, boolean setBreakpoint, boolean setInterpretationCode) {
        for (BacDrugTestResult astResult : astResults) {
            if (setBreakpoint) {
                astResult.setBreakPoint("");  // Set empty string for Breakpoint
            }

            // Set BreakpointId to null
            astResult.setBreakPointId("");

            // Set Guideline to empty string
            astResult.setGuideline("");

            // Set Year to empty string
            astResult.setYear("");

            // Set OrgCodeType to empty string
            astResult.setGermCodeType("");

            // Set OrgCode to empty string
            astResult.setSerovarGroup("");
            astResult.setWhonetOrgCode("");
            astResult.setGenusCode("");
            astResult.setGenusGroup("");
            astResult.setFamilyCode("");
            astResult.setAnaerobe("");
            astResult.setSubkingdomCode("");

            // Set BreakpointType to empty string
            astResult.setBreakPointType("");

            // Set Host to empty string
            astResult.setHost("");

            // Set WhonetTest to empty string
            astResult.setWhonetTest("");

            // Set Potency to empty string
            astResult.setPotency("");

            // Set SiteOfInfections to empty string
            astResult.setInfeSite("");

            // Set R (resistance) to null
            astResult.setR(null);

            // Set I (intermediate) to null
            astResult.setI(null);

            // Set SDD (susceptible-dose-dependent) to empty string
            astResult.setSdd("");

            // Set S (sensitive) to null
            astResult.setS(null);

            // Set Ecoff (epidemiological cutoff) to null
            astResult.setEcoff(null);

            // Set ReferenceRange to empty string
            astResult.setBreakPointRef("");

            // Set ReferenceTable to empty string
            astResult.setRefTable("");

            // Set ReferenceSequence to empty string
            astResult.setRefTableSeq("");

            // Set InterpretationCode to null, if setInterpretationCode is true
            if (setInterpretationCode) {
                astResult.setSensitiveNo("Uninterpretable");
                //astResult.setInterpretationCodeId(InterpretationCodeConsts.getDefault().getId());
            }
        }
    }

    private  void setEmptyBreakpointInfoTwo(BacDrugTestResult astResult){

        astResult.setBreakPoint("");  // Set empty string for Breakpoint
        // Set BreakpointId to null
        astResult.setBreakPointId("");
        // Set Guideline to empty string
        astResult.setGuideline("");
        // Set Year to empty string
        astResult.setYear("");
        // Set OrgCodeType to empty string
        astResult.setGermCodeType("");
        // Set OrgCode to empty string
        astResult.setSerovarGroup("");
        astResult.setWhonetOrgCode("");
        astResult.setGenusCode("");
        astResult.setGenusGroup("");
        astResult.setFamilyCode("");
        astResult.setAnaerobe("");
        astResult.setSubkingdomCode("");
        // Set BreakpointType to empty string
        astResult.setBreakPointType("");
        // Set Host to empty string
        astResult.setHost("");
        // Set WhonetTest to empty string
        astResult.setWhonetTest("");
        // Set Potency to empty string
        astResult.setPotency("");
        // Set SiteOfInfections to empty string
        astResult.setInfeSite("");
        // Set R (resistance) to null
        astResult.setR(null);
        // Set I (intermediate) to null
        astResult.setI(null);
        // Set SDD (susceptible-dose-dependent) to empty string
        astResult.setSdd("");
        // Set S (sensitive) to null
        astResult.setS(null);
        // Set Ecoff (epidemiological cutoff) to null
        astResult.setEcoff(null);
        // Set ReferenceRange to empty string
        astResult.setBreakPointRef("");
        // Set ReferenceTable to empty string
        astResult.setRefTable("");
        // Set ReferenceSequence to empty string
        astResult.setRefTableSeq("");
        astResult.setSensitiveNo("");
        astResult.setInterpNa("");
        astResult.setInterpDisplayColor("");
    }
    /*清空折点信息*/
    private void setEmptyBreakpointInfoOne(BacDrugTestResult astResult, boolean setBreakpoint, boolean setInterpretationCode) {
        //for (BacDrugTestResult astResult : astResults) {
        if (setBreakpoint) {
            astResult.setBreakPoint("");  // Set empty string for Breakpoint
        }

        // Set BreakpointId to null
        astResult.setBreakPointId("");

        // Set Guideline to empty string
        astResult.setGuideline("");

        // Set Year to empty string
        astResult.setYear("");

        // Set OrgCodeType to empty string
        astResult.setGermCodeType("");

        // Set OrgCode to empty string
        astResult.setSerovarGroup("");
        astResult.setWhonetOrgCode("");
        astResult.setGenusCode("");
        astResult.setGenusGroup("");
        astResult.setFamilyCode("");
        astResult.setAnaerobe("");
        astResult.setSubkingdomCode("");

        // Set BreakpointType to empty string
        astResult.setBreakPointType("");

        // Set Host to empty string
        astResult.setHost("");

        // Set WhonetTest to empty string
        astResult.setWhonetTest("");

        // Set Potency to empty string
        //astResult.setPotency("");

        // Set SiteOfInfections to empty string
        astResult.setInfeSite("");

        // Set R (resistance) to null
        astResult.setR(null);

        // Set I (intermediate) to null
        astResult.setI(null);

        // Set SDD (susceptible-dose-dependent) to empty string
        astResult.setSdd("");

        // Set S (sensitive) to null
        astResult.setS(null);

        // Set Ecoff (epidemiological cutoff) to null
        astResult.setEcoff(null);

        // Set ReferenceRange to empty string
        astResult.setBreakPointRef("");

        // Set ReferenceTable to empty string
        astResult.setRefTable("");

        // Set ReferenceSequence to empty string
        astResult.setRefTableSeq("");

        // Set InterpretationCode to null, if setInterpretationCode is true
        if (setInterpretationCode) {
            LambdaQueryWrapper<BacInterpretationCodeDict> query = new LambdaQueryWrapper<>();
            query.eq(BacInterpretationCodeDict::getDelFlag, 0);
            query.eq(BacInterpretationCodeDict::getStandardName, "Uninterpretable");
            List<BacInterpretationCodeDict> lst = bacInterpretationCodeDictMapper.selectList(query);
            if (!lst.isEmpty()) {
                astResult.setSensitiveNo(lst.get(0).getCode());
                astResult.setInterpNa(lst.get(0).getName());
                astResult.setInterpDisplayColor(lst.get(0).getDisplayColor());
            } else {
                astResult.setSensitiveNo("U");
                astResult.setInterpNa("");
                astResult.setInterpDisplayColor("#FFFFFF");
            }
            //astResult.setInterpretationCodeId(InterpretationCodeConsts.getDefault().getId());
        }
        //}
    }

    private void loadDictsAsync() {
        LambdaQueryWrapper<BacSiteOfInfectionDict> siteOfInfectionQuery = new LambdaQueryWrapper<>();
        siteOfInfectionQuery.eq(BacSiteOfInfectionDict::getDelFlag, 0);
        siteOfInfectionQuery.orderByAsc(BacSiteOfInfectionDict::getDisplayOrder);
        List<BacSiteOfInfectionDict> siteOfInfections = bacSiteOfInfectionDictMapper.selectList(siteOfInfectionQuery);

        SiteOfInfections = siteOfInfections;

        // Load ASTTestMethods
        LambdaQueryWrapper<BacAstTestMthDict> bacAstTestMthDictQuery = new LambdaQueryWrapper<>();
        bacAstTestMthDictQuery.eq(BacAstTestMthDict::getDelFlag, 0);
        List<BacAstTestMthDict> astTestMethods = bacAstTestMthDictMapper.selectList(bacAstTestMthDictQuery);

        ASTTestMethods = astTestMethods;  // Assuming this is an instance variable

        // Load InterpretationCodes
        LambdaQueryWrapper<BacInterpretationCodeDict> bacInterpretationCodeDictQuery = new LambdaQueryWrapper<>();
        bacInterpretationCodeDictQuery.eq(BacInterpretationCodeDict::getDelFlag, 0);
        List<BacInterpretationCodeDict> interpretationCodes = bacInterpretationCodeDictMapper.selectList(bacInterpretationCodeDictQuery); //interpretationCodeRepository.getQueryableAsync().thenApply(InterpretationCodeRepository::getAll).get();

        InterpretationCodes = interpretationCodes;
    }

    private String formatResult(String result, BigDecimal[] results) {
        // Implement result formatting logic here
        return result; // Placeholder return statement
    }

    public static List<String> getPastTenYears() {
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();

        // 创建一个 List 来存储过去 10 年的年份
        List<String> yearsList = new ArrayList<>();

        // 往 List 中添加从当前年份往回推 10 年的年份
        for (int i = 0; i < 10; i++) {
            yearsList.add(String.valueOf(currentYear - i));
        }

        return yearsList;
    }

    /*计算敏感度*/
    public BacInterpretationCodeDict getInterpretationCode(BacAstTestMthDict aSTTestMethod, BigDecimal result, BacBreakPoint applicableBreakpoint) {
        if (false) {
            return null;/*关闭折点结算*/
        }
        if (CollectionUtils.isEmpty(InterpretationCodes)) {
            LambdaQueryWrapper<BacInterpretationCodeDict> query = new LambdaQueryWrapper<>();
            query.eq(BacInterpretationCodeDict::getDelFlag, 0);
            InterpretationCodes = bacInterpretationCodeDictMapper.selectList(query);
        }

        BacInterpretationCodeDict U = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("BLAC")).findFirst().orElse(null);

        BacInterpretationCodeDict R = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("Resistant")).findFirst().orElse(null);

        BacInterpretationCodeDict NS = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("NonSusceptible")).findFirst().orElse(null);

        BacInterpretationCodeDict S = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("Susceptible")).findFirst().orElse(null);

        BacInterpretationCodeDict I = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("Intermediate")).findFirst().orElse(null);

        BacInterpretationCodeDict SDD = InterpretationCodes.stream().filter(p -> p.getStandardName().equals("SusceptibleDoseDependent")).findFirst().orElse(null);
        //K-B
        if (ToolsUtils.isNotEmpty(aSTTestMethod) && (aSTTestMethod.getCode().equals("D") || aSTTestMethod.getCode().equals("K-B") || aSTTestMethod.getCode().equals("DISK"))) {
            try {
                // Susceptible
                String s = applicableBreakpoint.getS();
                if(ToolsUtils.isNotEmpty(s)){
                    BigDecimal bigDecimal;
                    if(s.contains("/")){
                        bigDecimal = new BigDecimal(s.split("/")[0]);
                    }else {
                        bigDecimal = new BigDecimal(s);
                    }
                    if(ToolsUtils.isNotEmpty(bigDecimal)){
                        if (result.compareTo(bigDecimal) >= 0) {
                            return S;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // Resistant
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getR()) && result.compareTo(new BigDecimal(applicableBreakpoint.getR())) <= 0) {
                    return R;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                // Intermediate
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getI()) && !applicableBreakpoint.getI().trim().equals("-")) {
                    String[] range = applicableBreakpoint.getI().split("-");
                    if (range.length == 1) {
                        try {
                            BigDecimal tempResult = new BigDecimal(range[0].trim());
                            if (result.compareTo(tempResult) == 0) {
                                return I;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                    if (range.length == 2) {
                        try {
                            BigDecimal min = new BigDecimal(range[0].trim());
                            BigDecimal max = new BigDecimal(range[1].trim());
                            if (result.compareTo(min) >= 0 && result.compareTo(max) <= 0) {
                                return I;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getSdd()) && !applicableBreakpoint.getSdd().trim().equals("-")) {
                    String[] range = applicableBreakpoint.getSdd().split("-");
                    if (range.length == 1) {
                        try {
                            BigDecimal tempResult = new BigDecimal(range[0].trim());
                            if (result.compareTo(tempResult) == 0) {
                                return SDD;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                    if (range.length == 2) {
                        try {
                            BigDecimal min = new BigDecimal(range[0].trim());
                            BigDecimal max = new BigDecimal(range[1].trim());
                            if (result.compareTo(min) >= 0 && result.compareTo(max) <= 0) {
                                return SDD;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // ECOFF
                if (applicableBreakpoint.getEcvEcoff() != null) {
                    if (result.compareTo(new BigDecimal(applicableBreakpoint.getEcvEcoff())) >= 0) {
                        return InterpretationCodes.stream().filter(p -> p.getId().equals("WT")).findFirst().orElse(null);
                    }
                    if (result.compareTo(new BigDecimal(applicableBreakpoint.getEcvEcoff())) < 0) {
                        return InterpretationCodes.stream().filter(p -> p.getId().equals("NWT")).findFirst().orElse(null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                //NS
                if (ToolsUtils.isEmpty(applicableBreakpoint.getR()) || (ToolsUtils.isNotEmpty(applicableBreakpoint.getR()) && "0".equals(applicableBreakpoint.getR()))) {
                    return NS;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (ToolsUtils.isNotEmpty(aSTTestMethod) && ToolsUtils.isNotEmpty(aSTTestMethod.getCode()) && aSTTestMethod.getCode().equals("MIC")) {

            try {
                // Susceptible
                String s = applicableBreakpoint.getS();
                if(ToolsUtils.isNotEmpty(s)){
                    BigDecimal bigDecimal;
                    if(s.contains("/")){
                        bigDecimal = new BigDecimal(s.split("/")[0]);
                    }else {
                        bigDecimal = new BigDecimal(s);
                    }
                    if(ToolsUtils.isNotEmpty(bigDecimal)){
                        if (result.compareTo(bigDecimal) <= 0) {
                            return S;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // Resistant
                if (applicableBreakpoint.getR() != null && result.compareTo(new BigDecimal(applicableBreakpoint.getR())) >= 0) {
                    return R;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // Intermediate
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getI()) && !applicableBreakpoint.getI().trim().equals("-")) {
                    String[] range = applicableBreakpoint.getI().split("-");
                    if (range.length == 1) {
                        try {
                            BigDecimal tempResult = new BigDecimal(range[0].trim());
                            if (result.compareTo(tempResult) == 0) {
                                return I;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                    if (range.length == 2) {
                        try {
                            BigDecimal min = new BigDecimal(range[0].trim());
                            BigDecimal max = new BigDecimal(range[1].trim());
                            if (result.compareTo(min) >= 0 && result.compareTo(max) <= 0) {
                                return I;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // SDD
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getSdd()) && !applicableBreakpoint.getSdd().trim().equals("-")) {
                    String[] range = applicableBreakpoint.getSdd().split("-");
                    if (range.length == 1) {
                        try {
                            BigDecimal tempResult = new BigDecimal(range[0].trim());
                            if (result.compareTo(tempResult) == 0) {
                                return SDD;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                    if (range.length == 2) {
                        try {
                            BigDecimal min = new BigDecimal(range[0].trim());
                            BigDecimal max = new BigDecimal(range[1].trim());
                            if (result.compareTo(min) >= 0 && result.compareTo(max) <= 0) {
                                return SDD;
                            }
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                // ECOFF
                if (ToolsUtils.isNotEmpty(applicableBreakpoint.getEcvEcoff())) {
                    if (result.compareTo(new BigDecimal(applicableBreakpoint.getEcvEcoff())) <= 0) {
                        return InterpretationCodes.stream().filter(p -> p.getStandardName().equals("WildType")).findFirst().orElse(null);
                    }
                    if (result.compareTo(new BigDecimal(applicableBreakpoint.getEcvEcoff())) > 0) {
                        return InterpretationCodes.stream().filter(p -> p.getStandardName().equals("NonWildType")).findFirst().orElse(null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                //NS
                if (ToolsUtils.isEmpty(applicableBreakpoint.getR()) || (ToolsUtils.isNotEmpty(applicableBreakpoint.getR()) && "0".equals(applicableBreakpoint.getR()))) {
                    return NS;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
